const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const jwt = require('jsonwebtoken')
const SECRET = 'asdfta219*&%^jWJSHFJ'


router.post('/addStation', async (req, res) => {
    //token
    const result = jwt.verify(req.body.token, SECRET)
    let sql = 'select departmentId from user_role where username = ?'
    db.base(sql, result.username, response => {
        // console.log(response)
        // console.log(req.body)
        //验证成功则判断是否已经存在该岗位
        if(response.length > 0  && response[0].departmentId === 999) {
            let sql = 'select * from stationInfo where station_name = ? and department_name = ? and region = ? '
            //构造数据
            let department = req.body.department.split('(')
            let region = department[1].split(')')
            let data = [req.body.stationName,department[0],region[0]]
            db.base(sql, data, response => {
                // console.log(response.length)
                // 如果为0则可以允许该岗位添加，添加成功返回提示
                if (response.length === 0) {
                    //先获取该部门的id
                    let data = {
                        'station_name': req.body.stationName,
                        'clock_in': req.body.clockIn,
                        'clock_out': req.body.clockOut,
                        'average_salary': 0,
                        'number_of_jobs': 0,
                        'department_id': req.body.department_id
                    }
                    console.log(data)
                    let sql = 'insert into station set ?'
                    db.base(sql, data, () => {
                        res.json({
                            'code': 200,
                            'result': 'true',
                            'type': 'addStation_success',
                            'content': '成功添加新岗位'
                        })
                    })
                }
                //否则返回错误提示
                else {
                    res.json({
                        'code': 403,
                        'result': 'false',
                        'type': 'station_exist',
                        'content': '岗位已存在'
                    })
                }
            })
        }
        else {
            res.json({
                'code': 403,
                'result': 'false',
                'type': 'non_access',
                'content': '无权限'
            })


        }
    })
})

module.exports = router
